<template>
  <div>
    <div id="level" ref="levelRef" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount } from "vue";
const levelRef = ref(null);

let levleChart = null;

const originData = ref([
  { value: 103, name: "S级", percent: "80%-100%" },
  { value: 83, name: "A级", percent: "60%-80%" },
  { value: 63, name: "B级", percent: "40%-60%" },
  { value: 33, name: "C级", percent: "20%-40%" },
  { value: 13, name: "D级", percent: "0-20%" },
]);
const customerColor = [
  "#5470c6",
  "#91cc75",
  "#fac858",
  "#ee6666",
  "#73c0de",
  "#3ba272",
  "#fc8452",
  "#9a60b4",
  "#ea7ccc",
];

const initData = () => {
  levleChart = echarts.init(levelRef.value);

  const option = {
    title: {
      text: "评级统计",
      left: "20",
      top: "20",
    },
    tooltip: {
      trigger: "item",
      formatter: (data) => {
        return `
          <div style="font-size: 14px; color: #000; text-align: left">
            <div>评级：${data.name}</div>
            <div>占比：${data.percent}</div>
            <div>人数：${data.value}</div>
          </div>
        `;
      },
    },
    // 红橙黄绿青蓝紫
    color: customerColor,
    legend: {
      orient: "vertical",
      right: 50,
      top: 60,
      bottom: 20,
      data: originData.value.map((item) => item.name),
    },
    series: [
      {
        name: "Radius Mode",
        type: "pie",
        radius: [0, "75%"],
        center: ["50%", "50%"],
        roseType: "radius",
        itemStyle: {
          borderRadius: 5,
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
          },
        },
        data: originData.value,
      },
    ],
  };

  option && levleChart.setOption(option);
};

const resizeChart = () => {
  levleChart.resize();
};

onBeforeUnmount(() => {
  levleChart.dispose();
  window.removeEventListener("resize", resizeChart);
});

onMounted(() => {
  initData();
  window.addEventListener("resize", resizeChart);
});
</script>
